singleApp.controller('recipesCtrl', ['$http', '$scope', '$sce', 'PageService', function ($http, $scope, $sce, PageService) {
    $scope.list = [];
    $scope.Page = {
        id: "",
        pageindex: 1,
        pagesize: "20",
        TotalPages: 0,
        TotalRecords: 0,
        PageWindowSize: 10,
        PageRange: [],
    };
    $scope.model_select_all = false;

    $scope.model_pagesizelist = [
        { value: '20', label: '20' },
        { value: '50', label: '50' },
        { value: '100', label: '100' },
        { value: '200', label: '200' },
    ];

    $scope.selectAll = function () {
        $scope.model_select_all = !$scope.model_select_all;
        angular.forEach($scope.list, function (data, index, array) {
            data.selected = $scope.model_select_all;
        });
    };

    //Init
    $scope.init = function () {
        layer.load(2);

        var parms = [];
        parms.push("id=" + $scope.Page.id);
        parms.push("pageindex=" + $scope.Page.pageindex);
        parms.push("pagesize=" + $scope.Page.pagesize);
        var api_url = window.singleConfig.rootUrl + "api/admin/RecipeService/pageList?" + parms.join("&");

        $http.get(api_url).then(function (result) {
            var data = result.data;
            angular.forEach(data.records, function (data, index, array) {
                data.selected = false;
                data.myImage = window.singleConfig.rootUrl + "/public/data/uploadRawFile/" + data.thumb;
                data.myCroppedImage = "";
                data.bounds = { left: 0, right: 0, top: 0, bottom: 0 };
            });

            $scope.list = data.records;
            $scope.Page.TotalPages = data.totalPages;
            $scope.Page.TotalRecords = data.count;
            $scope.Page.PageRange = PageService.getPageRange($scope.Page.pageindex, $scope.Page.PageWindowSize, $scope.Page.TotalPages);
            layer.closeAll();
        }, function () { });
    };

    $scope.init();

    $scope.GoToPage = function (page) {
        if (page == $scope.Page.pageindex)
            return;
        $scope.Page.pageindex = page;
        $scope.init();
    };

    $scope.search = function () {
        $scope.init();
    };

    $scope.changePageSize = function () {
        $scope.init();
    };

    $scope.delete = function (item) {
        layer.confirm('Are you sure to delete this recipe ?', { icon: 3, title: 'Message', btn: ['Confirm', 'Cancel'] }, function (index) {
            layer.load(2);
            var api_url = window.singleConfig.rootUrl + "api/admin/RecipeService/delete?recipeid=" + item.id;
            $http.get(api_url).then(function (result) {
                var data = result.data;
                angular.forEach($scope.list, function (data, index, array) {
                    if (item.id == data.id) {
                        $scope.list.splice(index, 1);
                        $scope.Page.TotalRecords = $scope.Page.TotalRecords - 1;
                    }
                });
                layer.closeAll();
            }, function () { });
        });
    };


    $scope.crop = function (item) {
        var index = layer.open({
            type: 1,
            shade: false,
            title: 'Crop Img - ' + item.title + "(" + item.id + ")" + "(Crop Index: " + item.cropindex + ")",
            content: $('#divCropImg_' + item.id),
            area: ['1200px', '650px'],
            cancel: function (index) {
                layer.close(index);
            }
        });
        item.openindex = index;
    };

    $scope.confirmCropImg = function (item) {
        var loadindex = layer.load(2);
        var api_url = window.singleConfig.rootUrl + "api/common/FileService/uploadCropedRawFile";
        $http({
            method: 'POST',
            url: api_url,
            data: $.param({
                img_content: item.myCroppedImage,
                filename: "small_" + item.thumb,
                recipeid: item.id,
                rawfilename: item.thumb,
            }),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
		.then(function (result) {
		    var data = result.data;
		    if (data.code == "success") {
		        layer.close(item.openindex);
		        layer.close(loadindex);
		        item.thumb = data.newrawfile;
		        item.selected = false;
		    }
		    else {
		        layer.close(item.openindex);
		        layer.close(loadindex);
		        layer.msg(data.message);
		    }
		},function (data) {
		    layer.close(item.openindex);
		    layer.close(loadindex);
		    layer.msg("Error to save croped image.");
		});
    };

    $scope.cropSelectedRecipes = function () {
        var found = false;
        angular.forEach($scope.list, function (data, index, array) {
            if (data.selected == true) {
                found = true;
            }
        });

        if (found == false) {
            layer.msg("Please select at least one recipe !");
            return;
        }

        var cropindex = 1;
        angular.forEach($scope.list, function (data, index, array) {
            if (data.selected == true) {
                data.cropindex = cropindex++;
                $scope.crop(data);
            }
        });
    };

    $scope.toggleStatus = function (recipe) {
        layer.load(2);
        var parms = [
           "id=" + recipe.id,
           "status=" + (parseInt(recipe.status) == 0 ? 1 : 0)
        ];

        var api_url = window.singleConfig.rootUrl + "api/admin/RecipeService/updateStatus?" + parms.join("&");
        $http.get(api_url).then(function (data) {
            recipe.status = parseInt(recipe.status) == 0 ? 1 : 0;
            layer.closeAll();
        }, function () { });
    };

    $scope.toggleLevelStatus = function (recipe) {
        layer.load(2);
        var parms = [
           "id=" + recipe.id,
           "level_status=" + (parseInt(recipe.level_status) == 1 ? 2 : 1)
        ];

        var api_url = window.singleConfig.rootUrl + "api/admin/RecipeService/updateLevelStatus?" + parms.join("&");
        $http.get(api_url).then(function (data) {
            recipe.level_status = parseInt(recipe.level_status) == 1 ? 2 : 1;
            layer.closeAll();
        }, function () { });
    };

    $scope.togglePostQuora = function (recipe) {
        layer.load(2);
        var parms = [
           "id=" + recipe.id,
           "is_post_quora=" + (parseInt(recipe.is_post_quora) == 1 ? 0 : 1)
        ];

        var api_url = window.singleConfig.rootUrl + "api/admin/RecipeService/updateIsPostQuora?" + parms.join("&");
        $http.get(api_url).then(function (data) {
            recipe.is_post_quora = parseInt(recipe.is_post_quora) == 1 ? 0 : 1;
            layer.closeAll();
        }, function () { });
    };

    /*
     * Recipe Context Menu
     */
    $scope.menuOptionsRecipe = [
            ['View', function ($itemScope) {
                window.open(window.singleConfig.rootUrl + "recipe/" + $itemScope.item.recipe_url);
            }],
            ['Edit', function ($itemScope) {

            }],
            ['Download',function($itemScope){
                window.open(window.singleConfig.rootUrl + "api/admin/RecipeService/download?recipeid="  + $itemScope.item.id);
            }],
            null,
            ['Toggle Status', function ($itemScope) {
                $scope.toggleStatus($itemScope.item);
            }],
            ['Toggle Level Status', function ($itemScope) {
                $scope.toggleLevelStatus($itemScope.item);
            }],
            ['Toggle Post Quora', function ($itemScope) {
                $scope.togglePostQuora($itemScope.item);
            }],
            null,
            ['Delete', function ($itemScope) {
                $scope.delete($itemScope.item);
            }]
    ];
}]);